import React, { Component, Fragment } from 'react';
import {
    Button, Form, Radio, Row, Input, Col, message,Card,DatePicker,Spin
} from 'antd';
import { connect } from 'dva';
import InputText from '@/components/Input/index';
import Preview from './preview';
import styles from './index.less';
import router from 'umi/router';
import moment from 'moment';
const { TextArea } = Input;
const { RangePicker} = DatePicker;
const RadioGroup = Radio.Group;
const dateFormat = 'YYYY-MM-DD';

@connect(({global, marketing, loading}) => ({
    oemInfo: global.oemInfo,
    marketing,
    loading: loading.effects['marketing/GetCouponById'],
    loading1: loading.effects['marketing/UpdateCoupon'],
}))

class ReleaseCards extends Component {
    constructor() {
        super();
        this.state= {
            ConditionType: 1,
            LimitCountValue: 'a',
            ConditionNum: '',
            WaiverAmountNum: '',
            textName: '',
            dateString: ['',''],
            editData: {}
        }
    }

    componentWillMount() {
      window.Isoption = false;
    }

    componentDidMount() {
      window.Isoption = true;
        this.requestCouponById()
    }

    requestCouponById =() => {
        const { dispatch, match } = this.props;
        dispatch({
            type: 'marketing/GetCouponById',
            payload: {
                Id: match.params.id?match.params.id: 0
            },
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            editData: res.Data,
                            name:res.Data.Name,
                            ConditionType: res.Data.Condition===0?'a':'b',
                            LimitCountType: res.Data.LimitCount===0?'a':'b',
                            ConditionNum: res.Data.Condition,
                            WaiverAmountNum: res.Data.WaiverAmount,
                            dateString:[moment(res.Data.ValidStartTime).format('YYYY-MM-DD'), moment(res.Data.ValidEndTime).format('YYYY-MM-DD')],
                            textName:res.Data.Description,
                        })
                    }
                },
                error: res=> {
                    console.log(res.Msg)
                }
            }
        })
    }

  handleSubmit =(e) => {
    e.preventDefault();
    const { dispatch, match } = this.props;
    this.props.form.validateFieldsAndScroll({force: true}, (err, values) => {
        if(!err) {
            dispatch({
                type: 'marketing/UpdateCoupon',
                payload: {
                    Id: match.params.id?match.params.id:0,
                    Name: values.Name,
                    TotalQty: values.TotalQty,
                    Description: values.Description,
                },
                callBack: {
                    success: res => {
                        if(res.Code ===0) {
                            message.success('保存成功');
                            router.replace({
                                pathname: `/${window.storeId}/marketing/coupon`,
                            });
                        }
                    },
                    error: res => {
                        message.error(res.Msg)
                    }
                }
            })
        }
    })}

   // 校验名
   checkName = (e) => {
    this.props.form.validateFields(['name'], { force: true });
  }

    // 修改名称
    onTextChange = (v) => {
        this.setState({ name: v.target.value  });
        this.props.form.setFieldsValue({
            Name: v.target.value
        })
    }

    // 说明
    textChange =(e) => {
        this.setState({
            textName: e.target.value
        })
    }

    render() {
        const {oemInfo, loading, loading1} = this.props;
        const { getFieldDecorator, getFieldValue} = this.props.form;
        const {LimitCountType, name, ConditionType, ConditionNum, WaiverAmountNum, dateString, textName, editData,textArea} = this.state;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: { span: 11 },
        };
        const formItemLayout2 = {
            labelCol: {span: 6},
            wrapperCol: { span: 16 },
        };
        return (
            <Form className={styles.contentBox} onSubmit={this.handleSubmit}>
                <Spin spinning={loading}>
                <Card bordered={false} className={styles.card}>
                        <Preview
                            title="优惠券"
                            oemInfo={oemInfo}
                            name={name}
                            ConditionType={ConditionType}
                            ConditionNum={ConditionNum}
                            WaiverAmountNum={WaiverAmountNum}
                            dateString={dateString}
                            textName={textName}
                        />
                        <div className={styles.right}>
                            <div className={styles.headText}>基本信息</div>
                            <Form.Item
                                label="优惠券名称"
                                {...formItemLayout}
                            >
                                {getFieldDecorator('Name', {
                                    initialValue: name,
                                    rules: [{
                                        required: true, message:'此项为必填项',whitespace: true
                                    }],
                                    validateTrigger: 'onBlur'
                                })(
                                    <InputText name="Name" onChange={this.onTextChange} onBlur={this.checkName} showtotal maxLength={10}/>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="发放总量"
                                {...formItemLayout2}
                                extra="修改优惠券总量时只能增加不能减少，请谨慎设置"
                            >
                                {getFieldDecorator('TotalQty', {
                                    initialValue: editData.TotalQty,
                                    rules: [
                                        {required: true, message:'此项为必填项'},
                                        {pattern: /^1*[1-9]\d{0,4}$/, message: '1~99999之间的数字'},
                                    ]
                                })(
                                    <Input addonAfter="张" style={{width: 115}}/>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="适用商品"
                                {...formItemLayout2}
                            >
                                {getFieldDecorator('type')(
                                    <span>全部商品可用</span>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="使用门槛"
                                {...formItemLayout2}
                                className={styles.Redio}
                            >
                                {getFieldDecorator('radio1', {initialValue: ConditionType})(
                                    <RadioGroup>
                                        <Row>
                                            <Col span={12}>
                                                <Radio value={'a'} disabled>无使用门槛</Radio>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={8}>
                                                <Radio value={'b'} disabled>订单满</Radio>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item>
                                                    {getFieldDecorator('Condition',
                                                      {initialValue: ConditionNum?ConditionNum:''}
                                                      )(
                                                        <Input addonAfter="元" style={{width: 115, marginLeft:8}} disabled/>
                                                   )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </RadioGroup>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="优惠内容"
                                {...formItemLayout2}
                            >
                                {getFieldDecorator('WaiverAmount', {
                                })(
                                    <span>
                                        <span>减免</span>
                                        <Input addonAfter="元" style={{width: 115, marginLeft:8}} disabled defaultValue={WaiverAmountNum}/>
                                    </span>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="用券时间"
                                {...formItemLayout}
                            >
                                {getFieldDecorator('Date', {
                                    initialValue: [moment(editData.ValidStartTime, dateFormat), moment(editData.ValidEndTime, dateFormat)],
                                })(
                                    <RangePicker format={dateFormat} disabled/>
                                )}
                            </Form.Item>
                            <div className={styles.footText}>领取和使用规则</div>
                            <Form.Item
                                label="每人限领次数"
                                {...formItemLayout2}
                                className={styles.Redio}
                            >
                                {getFieldDecorator('radio2', {
                                    initialValue: LimitCountType,
                                })(
                                    <RadioGroup onChange={this.onChangeLimitCount}>
                                        <Row>
                                            <Col span={12}>
                                                <Radio value={'a'} disabled>不限次数</Radio>
                                            </Col>
                                        </Row>
                                        <Row >
                                            <Col span={16}>
                                                <Form.Item>
                                                    <Radio value={'b'} disabled>
                                                        {
                                                            getFieldDecorator('LimitCount',{
                                                                initialValue: editData.LimitCount?editData.LimitCount:'',
                                                            })(<Input addonAfter="次" style={{width: 115}} disabled/>)
                                                        }
                                                    </Radio>
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </RadioGroup>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="使用说明"
                                {...formItemLayout}
                            >
                                {getFieldDecorator('Description', {
                                    initialValue: textName,
                                    rules: [{required: true, message:'此项为必填项'}]
                                })(
                                    <TextArea rows={3} maxLength={300} onChange={this.textChange}/>
                                )}
                            </Form.Item>
                        </div>
                    </Card>

                    <div className="xkd-bottom-actions">
                            <Button
                                htmlType="submit"
                                type="primary"
                                loading={loading1}
                            >
                            保存
                        </Button>
                    </div>
                </Spin>

            </Form>
        )
    }
}

export default Form.create()(ReleaseCards);
